from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from meiduo_admin.serializers.order import OrderInfoSerializer
from order.models import OrderInfo
from meiduo_admin.serializers.users import UsersSerializer
from meiduo_admin.utils import PageNumberPagination, PageNum


class Users(ReadOnlyModelViewSet):
    # 指定序列化器
    serializer_class =OrderInfoSerializer

    # 指定分页器
    pagination_class = PageNum
    # 认证
    permission_classes = [IsAdminUser]


    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id__contains=keyword)
    @action(methods=['put'],detail=True)
    def status(self,requset,pk):

        status = requset.data
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'error':'订单错误'})
        status = status.get('status')
        if status is None:
            return Response({'error': '订单状态错误'})

        order.status = status
        order.save()
        return Response({'status':status})


